package com.adong.tv.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.adong.tv.R;
import com.adong.tv.model.Movie;
import com.adong.tv.ui.adapter.EpisodeAdapter;
import com.adong.tv.ui.viewmodel.DetailViewModel;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;

import java.util.List;

/**
 * 详情页Activity
 */
public class DetailActivity extends FragmentActivity {
    
    public static final String EXTRA_MOVIE_ID = "movie_id";
    public static final int REQUEST_CODE_PLAY = 1001;  // 添加请求码
    
    private DetailViewModel viewModel;
    private ProgressBar progressBar;
    private View contentLayout;
    private ImageView posterImageView;
    private TextView titleTextView;
    private TextView remarkTextView;
    private TextView directorTextView;
    private TextView actorTextView;
    private TextView typeTextView;
    private TextView areaTextView;
    private TextView yearTextView;
    private TextView descTextView;
    private Button playButton;
    private RecyclerView episodesRecyclerView;
    private EpisodeAdapter episodeAdapter;
    
    // 当前播放的剧集
    private Movie.Episode currentPlayingEpisode;
    private List<Movie.Episode> episodes;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        
        // 初始化视图
        initViews();
        
        // 设置ViewModel
        viewModel = new ViewModelProvider(this).get(DetailViewModel.class);
        
        // 获取电影ID
        int movieId = getIntent().getIntExtra(EXTRA_MOVIE_ID, 0);
        if (movieId > 0) {
            loadMovieDetail(movieId);
        } else {
            Toast.makeText(this, R.string.error_load, Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 恢复播放状态高亮
        if (currentPlayingEpisode != null && episodeAdapter != null) {
            episodeAdapter.setCurrentPlayingEpisode(currentPlayingEpisode);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PLAY && resultCode == PlayerActivity.RESULT_PLAY_NEXT) {
            // 播放下一集
            playNextEpisode();
        }
    }
    
    /**
     * 初始化视图
     */
    private void initViews() {
        progressBar = findViewById(R.id.progress_bar);
        contentLayout = findViewById(R.id.layout_content);
        posterImageView = findViewById(R.id.iv_poster);
        titleTextView = findViewById(R.id.tv_title);
        remarkTextView = findViewById(R.id.tv_remark);
        directorTextView = findViewById(R.id.tv_director);
        actorTextView = findViewById(R.id.tv_actor);
        typeTextView = findViewById(R.id.tv_type);
        areaTextView = findViewById(R.id.tv_area);
        yearTextView = findViewById(R.id.tv_year);
        descTextView = findViewById(R.id.tv_desc);
        playButton = findViewById(R.id.btn_play);
        episodesRecyclerView = findViewById(R.id.rv_episodes);
        
        // 设置剧集适配器
        episodeAdapter = new EpisodeAdapter(episode -> {
            playEpisode(episode);
        });
        episodesRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        episodesRecyclerView.setAdapter(episodeAdapter);
    }
    
    /**
     * 加载电影详情
     */
    private void loadMovieDetail(int movieId) {
        progressBar.setVisibility(View.VISIBLE);
        contentLayout.setVisibility(View.GONE);
        
        viewModel.getMovieDetail(movieId).observe(this, result -> {
            progressBar.setVisibility(View.GONE);
            
            if (result.isSuccess() && result.getData() != null) {
                Movie movie = result.getData();
                updateUI(movie);
                contentLayout.setVisibility(View.VISIBLE);
            } else {
                Toast.makeText(this, result.getMessage(), Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }
    
    /**
     * 更新UI
     */
    private void updateUI(Movie movie) {
        // 设置标题和备注
        titleTextView.setText(movie.getVodName());
        remarkTextView.setText(movie.getVodRemarks());
        
        // 设置导演和演员
        directorTextView.setText(getString(R.string.detail_director) + movie.getVodDirector());
        actorTextView.setText(getString(R.string.detail_actor) + movie.getVodActor());
        
        // 设置类型、地区和年份
        typeTextView.setText(getString(R.string.detail_type) + movie.getTypeName());
        areaTextView.setText(getString(R.string.detail_area) + movie.getVodArea());
        yearTextView.setText(getString(R.string.detail_year) + movie.getVodYear());
        
        // 设置简介
        descTextView.setText(getString(R.string.detail_desc) + movie.getVodContent());
        
        // 加载海报
        Glide.with(this)
                .load(movie.getVodPic())
                .apply(new RequestOptions()
                        .transforms(new CenterCrop(), new RoundedCorners(16))
                        .placeholder(R.drawable.default_background)
                        .error(R.drawable.default_background))
                .into(posterImageView);
        
        // 设置播放按钮和剧集列表
        if (movie.getEpisodes() != null && !movie.getEpisodes().isEmpty()) {
            episodes = movie.getEpisodes();  // 保存剧集列表
            
            // 有剧集
            playButton.setOnClickListener(v -> {
                playEpisode(episodes.get(0));
            });
            
            // 设置剧集
            episodeAdapter.setEpisodes(episodes);
            episodesRecyclerView.setVisibility(View.VISIBLE);
            
            // 恢复播放状态
            if (currentPlayingEpisode != null) {
                episodeAdapter.setCurrentPlayingEpisode(currentPlayingEpisode);
            }
        } else {
            // 没有剧集，隐藏剧集列表
            episodesRecyclerView.setVisibility(View.GONE);
        }
    }
    
    /**
     * 播放剧集
     */
    private void playEpisode(Movie.Episode episode) {
        // 更新当前播放的剧集
        currentPlayingEpisode = episode;
        episodeAdapter.setCurrentPlayingEpisode(episode);
        
        Intent intent = new Intent(this, PlayerActivity.class);
        intent.putExtra(PlayerActivity.EXTRA_URL, episode.getUrl());
        intent.putExtra(PlayerActivity.EXTRA_TITLE, titleTextView.getText().toString());
        intent.putExtra(PlayerActivity.EXTRA_EPISODE, episode.getName());
        startActivityForResult(intent, REQUEST_CODE_PLAY);  // 使用startActivityForResult
    }
    
    /**
     * 播放下一集
     */
    private void playNextEpisode() {
        if (episodes != null && currentPlayingEpisode != null) {
            // 查找当前播放剧集的索引
            int currentIndex = -1;
            for (int i = 0; i < episodes.size(); i++) {
                if (episodes.get(i).getUrl().equals(currentPlayingEpisode.getUrl())) {
                    currentIndex = i;
                    break;
                }
            }
            
            // 如果找到当前剧集，并且还有下一集
            if (currentIndex != -1 && currentIndex < episodes.size() - 1) {
                // 播放下一集
                playEpisode(episodes.get(currentIndex + 1));
            } else {
                // 已经是最后一集
                Toast.makeText(this, "已经是最后一集了", Toast.LENGTH_SHORT).show();
            }
        }
    }
} 